package com.ossean.projectmanager.hotwords;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ossean.projectmanager.lasttabledao.OpenSourceProjectDao;
import com.ossean.projectmanager.lasttabledao.PointersDao;
import com.ossean.projectmanager.lasttabledao.TagDao;
import com.ossean.projectmanager.lasttabledao.TaggingsDao;
import com.ossean.projectmanager.model.Hotword;
import com.ossean.projectmanager.model.OpenSourceProject;
import com.ossean.projectmanager.model.Taggings;

@Component("updatetagsandtaggings")
public class UpdateTagsAndTaggings {
	Logger logger = Logger.getLogger(this.getClass());
	
	@Resource
	private TaggingsDao taggingsDao;
	@Resource
	private OpenSourceProjectDao ospDao;
	@Resource
	private TagDao tagsDao;
	@Resource
	private PointersDao pointersDao;
	@Qualifier("inserthotwords")
	@Autowired
	private InsertHotwords insertClass;
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void update(OpenSourceProject project, List<String> projectTagList, String tagsNew, int count, String sourceTableName, String targetTableName, List<Hotword> hotwordsList, List<String> updateDisagreeNumTagNameList, Map<String, Integer> tagCountMap){
		//对新的项目标签(tags)属性进行更新
		ospDao.updateTagsOfProject(project.getId(), tagsNew);
		//对新加的标签进行遍历
		for(int i = projectTagList.size() - 1; i >= projectTagList.size() - count; i--){
			String tagName = projectTagList.get(i);
			//取出相应tagName的标签
			List<Integer> tagIds = tagsDao.getIdByName(tagName);
			if(tagIds.size() == 0){
				//表示tag不存在
				logger.fatal("tag: " + tagName + " doesn't exist! We will insert one");
				tagsDao.insertTag(tagName);
				i++;
				continue;
			}else{
				//表示标签存在
				int tagId = tagIds.get(0);
				//构造taggings对象
				Taggings taggings = new Taggings();
				taggings.setTag_id(tagId);
				taggings.setTaggable_id(project.getId());
				taggings.setDisagree_num(0);//初始化的disagree_num为0
				taggings.setTaggable_type("OpenSourceProject");
				taggings.setContext("tags");
				taggings.setTag_source("FromRelativeMemo");
				List<Taggings> tmp = taggingsDao.findTaggings(taggings);
				if(tmp.size() != 0){
					//表示已经存在相应的taggings记录
					continue;
				}else{
					//将新记录插入taggings表中
					taggingsDao.insertTaggings(taggings);
				}
			}
		}
		
		//将项目对应的热词插入hotwords表 在insert函数中进行指针的更新 同时更新已经存在在项目标签属性中的标签disagree_num值
		insertClass.insert(hotwordsList, sourceTableName, targetTableName, project.getId() + 1, updateDisagreeNumTagNameList, tagCountMap, project);
		
		logger.info("当前项目" + project.getName() + "的更新操作完成");
	}
}
